<template>
  <view class="test-subscription-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">微信订阅消息测试</text>
      <text class="page-subtitle">Spring Boot API 测试工具</text>
    </view>

    <!-- 配置信息卡片 -->
    <view class="info-card">
      <view class="card-header">
        <text class="card-title">配置信息</text>
        <view class="status-indicator" :class="configStatus">
          <text class="status-text">{{ configStatusText }}</text>
        </view>
      </view>
      
      <view class="config-info">
        <view class="config-item">
          <text class="config-label">当前AppID:</text>
          <text class="config-value">{{ currentAppId || '未获取' }}</text>
        </view>
        <view class="config-item">
          <text class="config-label">后端AppID:</text>
          <text class="config-value">{{ backendAppId }}</text>
        </view>
        <view class="config-item">
          <text class="config-label">模板ID:</text>
          <text class="config-value">{{ templateId }}</text>
        </view>
        <view class="config-item">
          <text class="config-label">用户OpenID:</text>
          <text class="config-value">{{ userOpenId || '未获取' }}</text>
        </view>
      </view>
    </view>

    <!-- 测试步骤 -->
    <view class="test-steps">
      <!-- 步骤1: 检查配置 -->
      <view class="step-card" :class="{ 'step-completed': step1Completed }">
        <view class="step-header">
          <view class="step-number">1</view>
          <text class="step-title">检查配置信息</text>
          <view class="step-status" v-if="step1Completed">✅</view>
        </view>
        <view class="step-content">
          <text class="step-desc">验证小程序AppID与后端配置是否一致</text>
          <button 
            class="step-btn primary" 
            @click="checkConfiguration"
            :loading="checking"
          >
            {{ checking ? '检查中...' : '检查配置' }}
          </button>
        </view>
      </view>

      <!-- 步骤2: 获取OpenID -->
      <view class="step-card" :class="{ 'step-completed': step2Completed, 'step-disabled': !step1Completed }">
        <view class="step-header">
          <view class="step-number">2</view>
          <text class="step-title">获取用户OpenID</text>
          <view class="step-status" v-if="step2Completed">✅</view>
        </view>
        <view class="step-content">
          <text class="step-desc">通过微信登录获取用户OpenID</text>
          <button 
            class="step-btn primary" 
            @click="getUserOpenId"
            :loading="gettingOpenId"
            :disabled="!step1Completed"
          >
            {{ gettingOpenId ? '获取中...' : '获取OpenID' }}
          </button>
        </view>
      </view>

      <!-- 步骤3: 订阅消息 -->
      <view class="step-card" :class="{ 'step-completed': step3Completed, 'step-disabled': !step2Completed }">
        <view class="step-header">
          <view class="step-number">3</view>
          <text class="step-title">订阅消息模板</text>
          <view class="step-status" v-if="step3Completed">✅</view>
        </view>
        <view class="step-content">
          <text class="step-desc">请求用户授权订阅消息模板</text>
          <button 
            class="step-btn primary" 
            @click="subscribeMessage"
            :loading="subscribing"
            :disabled="!step2Completed"
          >
            {{ subscribing ? '订阅中...' : '订阅消息' }}
          </button>
        </view>
      </view>

      <!-- 步骤4: 发送测试消息 -->
      <view class="step-card" :class="{ 'step-completed': step4Completed, 'step-disabled': !step3Completed }">
        <view class="step-header">
          <view class="step-number">4</view>
          <text class="step-title">发送测试消息</text>
          <view class="step-status" v-if="step4Completed">✅</view>
        </view>
        <view class="step-content">
          <text class="step-desc">调用Spring Boot API发送订阅消息</text>
          <view class="send-options">
            <button 
              class="step-btn success" 
              @click="sendTestMessage('confirmed')"
              :loading="sending"
              :disabled="!step3Completed"
            >
              发送确认格式消息
            </button>
            <button 
              class="step-btn default" 
              @click="sendTestMessage('minimal')"
              :loading="sending"
              :disabled="!step3Completed"
            >
              发送最简消息
            </button>
            <button 
              class="step-btn default" 
              @click="sendTestMessage('debug')"
              :loading="sending"
              :disabled="!step3Completed"
            >
              调试模式发送
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 测试结果 -->
    <view class="result-card" v-if="testResults.length > 0">
      <view class="card-header">
        <text class="card-title">测试结果</text>
        <button class="clear-btn" @click="clearResults">清空</button>
      </view>
      
      <scroll-view scroll-y class="results-scroll">
        <view 
          class="result-item" 
          v-for="(result, index) in testResults" 
          :key="index"
          :class="result.success ? 'result-success' : 'result-error'"
        >
          <view class="result-header">
            <text class="result-title">{{ result.title }}</text>
            <text class="result-time">{{ formatTime(result.timestamp) }}</text>
          </view>
          <view class="result-content">
            <text class="result-text">{{ result.message }}</text>
          </view>
          <view class="result-details" v-if="result.details">
            <text class="details-text">{{ result.details }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 快速诊断按钮 -->
    <view class="quick-actions">
      <button class="action-btn diagnose" @click="quickDiagnose">
        🔍 快速诊断412错误
      </button>
      <button class="action-btn flow" @click="getTestFlow">
        📋 获取完整测试流程
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 配置信息
      currentAppId: '',
      backendAppId: 'wxfb22784840ae6d0c',
      templateId: 'zvaRsziQ2U139jQdNUSSX8cCgyqHe_r5xIsuGo36wR8',
      userOpenId: '',
      
      // 步骤状态
      step1Completed: false,
      step2Completed: false,
      step3Completed: false,
      step4Completed: false,
      
      // 加载状态
      checking: false,
      gettingOpenId: false,
      subscribing: false,
      sending: false,
      
      // 测试结果
      testResults: [],
      
      // 订阅权限
      hasSubscribePermission: false
    }
  },
  
  computed: {
    configStatus() {
      if (!this.currentAppId) return 'status-unknown'
      return this.currentAppId === this.backendAppId ? 'status-match' : 'status-mismatch'
    },
    
    configStatusText() {
      if (!this.currentAppId) return '未检查'
      return this.currentAppId === this.backendAppId ? '配置匹配' : '配置不匹配'
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  methods: {
    // 初始化页面
    initPage() {
      this.addResult('系统', '页面初始化完成', '开始微信订阅消息测试流程', true)
    },
    
    // 步骤1: 检查配置信息
    async checkConfiguration() {
      this.checking = true
      
      try {
        // #ifdef MP-WEIXIN
        const accountInfo = wx.getAccountInfoSync()
        this.currentAppId = accountInfo.miniProgram.appId
        
        console.log('当前小程序AppID:', this.currentAppId)
        console.log('后端配置AppID:', this.backendAppId)
        
        const isMatch = this.currentAppId === this.backendAppId
        
        this.addResult(
          '配置检查',
          isMatch ? '✅ AppID配置匹配' : '❌ AppID配置不匹配',
          `当前: ${this.currentAppId}\n后端: ${this.backendAppId}`,
          isMatch
        )
        
        if (isMatch) {
          this.step1Completed = true
          uni.showToast({
            title: '配置检查通过',
            icon: 'success'
          })
        } else {
          uni.showModal({
            title: '配置不匹配',
            content: `当前小程序AppID与后端配置不一致，这会导致订阅消息发送失败。\n\n当前: ${this.currentAppId}\n后端: ${this.backendAppId}`,
            showCancel: false
          })
        }
        // #endif
        
        // #ifndef MP-WEIXIN
        this.addResult('配置检查', '⚠️ 非微信小程序环境', '无法获取AppID信息', false)
        // #endif
        
      } catch (error) {
        console.error('检查配置失败:', error)
        this.addResult('配置检查', '❌ 检查失败', error.message, false)
      } finally {
        this.checking = false
      }
    },
    
    // 步骤2: 获取用户OpenID
    async getUserOpenId() {
      this.gettingOpenId = true
      
      try {
        // 先检查本地存储
        let openid = uni.getStorageSync('user_openid')
        
        if (openid) {
          this.userOpenId = openid
          this.step2Completed = true
          this.addResult('OpenID获取', '✅ 从本地获取成功', `OpenID: ${openid.substring(0, 10)}...`, true)
          return
        }
        
        // #ifdef MP-WEIXIN
        // 通过微信登录获取
        uni.login({
          provider: 'weixin',
          success: async (loginRes) => {
            console.log('微信登录成功:', loginRes)
            
            if (!loginRes.code) {
              this.addResult('OpenID获取', '❌ 登录失败', '未获取到登录凭证', false)
              return
            }
            
            try {
              // 这里需要调用您的后端接口获取OpenID
              // 由于您使用的是Spring Boot，需要创建对应的接口
              const result = await this.callBackendAPI('/wechat/getOpenId', {
                code: loginRes.code
              })
              
              if (result.success && result.data.openid) {
                this.userOpenId = result.data.openid
                uni.setStorageSync('user_openid', this.userOpenId)
                this.step2Completed = true
                
                this.addResult(
                  'OpenID获取', 
                  '✅ 获取成功', 
                  `OpenID: ${this.userOpenId.substring(0, 10)}...`, 
                  true
                )
              } else {
                this.addResult('OpenID获取', '❌ 获取失败', result.message || '未知错误', false)
              }
            } catch (error) {
              console.error('获取OpenID失败:', error)
              this.addResult('OpenID获取', '❌ 接口调用失败', error.message, false)
            }
          },
          fail: (error) => {
            console.error('微信登录失败:', error)
            this.addResult('OpenID获取', '❌ 微信登录失败', error.errMsg, false)
          },
          complete: () => {
            this.gettingOpenId = false
          }
        })
        // #endif
        
        // #ifndef MP-WEIXIN
        this.addResult('OpenID获取', '⚠️ 非微信小程序环境', '无法获取OpenID', false)
        this.gettingOpenId = false
        // #endif
        
      } catch (error) {
        console.error('获取OpenID异常:', error)
        this.addResult('OpenID获取', '❌ 异常', error.message, false)
        this.gettingOpenId = false
      }
    },
    
    // 步骤3: 订阅消息
    async subscribeMessage() {
      this.subscribing = true
      
      try {
        // #ifdef MP-WEIXIN
        const result = await uni.requestSubscribeMessage({
          tmplIds: [this.templateId]
        })
        
        console.log('订阅结果:', result)
        
        const subscribeStatus = result[this.templateId]
        
        if (subscribeStatus === 'accept') {
          this.hasSubscribePermission = true
          this.step3Completed = true
          
          this.addResult(
            '消息订阅',
            '✅ 订阅成功',
            '用户同意接收订阅消息',
            true
          )
          
          uni.showToast({
            title: '订阅成功',
            icon: 'success'
          })
          
          // 订阅成功后可以立即测试发送
          setTimeout(() => {
            this.sendTestMessage('confirmed')
          }, 1000)
          
        } else if (subscribeStatus === 'reject') {
          this.addResult(
            '消息订阅',
            '❌ 用户拒绝',
            '用户拒绝接收订阅消息',
            false
          )
          
          uni.showModal({
            title: '订阅被拒绝',
            content: '您拒绝了订阅消息，将无法接收课程通知。可以在小程序设置中重新开启。',
            showCancel: false
          })
          
        } else {
          this.addResult(
            '消息订阅',
            '⚠️ 状态未知',
            `订阅状态: ${subscribeStatus}`,
            false
          )
        }
        // #endif
        
        // #ifndef MP-WEIXIN
        this.addResult('消息订阅', '⚠️ 非微信小程序环境', '无法测试订阅功能', false)
        // #endif
        
      } catch (error) {
        console.error('订阅失败:', error)
        this.addResult('消息订阅', '❌ 订阅异常', error.message, false)
      } finally {
        this.subscribing = false
      }
    },
    
    // 步骤4: 发送测试消息
    async sendTestMessage(type = 'confirmed') {
      if (!this.hasSubscribePermission) {
        uni.showModal({
          title: '未订阅消息',
          content: '请先完成消息订阅步骤',
          showCancel: false
        })
        return
      }
      
      this.sending = true
      
      try {
        let endpoint = ''
        let title = ''
        
        switch (type) {
          case 'confirmed':
            endpoint = '/wechat/sendConfirmed'
            title = '确认格式消息'
            break
          case 'minimal':
            endpoint = '/wechat/sendMinimal'
            title = '最简消息'
            break
          case 'debug':
            endpoint = '/wechat/debug412'
            title = '调试模式消息'
            break
          default:
            endpoint = '/wechat/sendRealMessage'
            title = '默认消息'
        }
        
        const result = await this.callBackendAPI(endpoint)
        
        if (result.success) {
          this.step4Completed = true
          this.addResult(
            `${title}发送`,
            '✅ 发送成功',
            result.message || '消息已发送，请查看微信通知',
            true
          )
          
          uni.showToast({
            title: '发送成功',
            icon: 'success'
          })
        } else {
          this.addResult(
            `${title}发送`,
            '❌ 发送失败',
            result.message || '未知错误',
            false
          )
          
          // 如果是412错误，提供诊断建议
          if (result.message && result.message.includes('412')) {
            setTimeout(() => {
              this.quickDiagnose()
            }, 1000)
          }
        }
        
      } catch (error) {
        console.error('发送消息失败:', error)
        this.addResult(
          '消息发送',
          '❌ 发送异常',
          error.message,
          false
        )
      } finally {
        this.sending = false
      }
    },
    
    // 快速诊断412错误
    async quickDiagnose() {
      try {
        const result = await this.callBackendAPI('/wechat/diagnose412')
        
        if (result.success) {
          const diagnosis = result.data
          
          let content = '🔍 412错误诊断结果:\n\n'
          
          if (diagnosis.errorCauses) {
            content += '主要原因:\n'
            diagnosis.errorCauses.forEach(cause => {
              content += `${cause}\n`
            })
            content += '\n'
          }
          
          if (diagnosis.immediateSolutions) {
            content += '解决方案:\n'
            diagnosis.immediateSolutions.forEach(solution => {
              content += `${solution}\n`
            })
          }
          
          uni.showModal({
            title: '412错误诊断',
            content: content,
            showCancel: false
          })
        }
      } catch (error) {
        console.error('诊断失败:', error)
      }
    },
    
    // 获取完整测试流程
    async getTestFlow() {
      try {
        const result = await this.callBackendAPI('/wechat/testFlow')
        
        if (result.success) {
          const flow = result.data
          
          let content = '📋 完整测试流程:\n\n'
          
          if (flow.step1_config_check) {
            content += '1. 配置检查:\n'
            content += `AppID: ${flow.step1_config_check.appid}\n`
            content += `模板ID: ${flow.step1_config_check.templateId}\n\n`
          }
          
          if (flow.step2_token_check) {
            content += '2. Token检查:\n'
            content += `状态: ${flow.step2_token_check.success ? '✅' : '❌'}\n\n`
          }
          
          content += '3. 按顺序执行上述测试步骤\n'
          content += '4. 如遇问题，使用快速诊断功能'
          
          uni.showModal({
            title: '测试流程指导',
            content: content,
            showCancel: false
          })
        }
      } catch (error) {
        console.error('获取流程失败:', error)
      }
    },
    
    // 调用后端API的通用方法
    callBackendAPI(endpoint, data = null) {
      return new Promise((resolve) => {
        const config = {
          url: `http://localhost:9090${endpoint}`,
          method: data ? 'POST' : 'GET',
          success: (res) => {
            console.log(`API ${endpoint} 响应:`, res)
            
            if (res.statusCode === 200) {
              resolve({
                success: res.data.code === '200',
                data: res.data.data,
                message: res.data.message
              })
            } else {
              resolve({
                success: false,
                message: `HTTP ${res.statusCode}: ${res.data.message || '请求失败'}`
              })
            }
          },
          fail: (error) => {
            console.error(`API ${endpoint} 失败:`, error)
            resolve({
              success: false,
              message: `网络错误: ${error.errMsg || '请求失败'}`
            })
          }
        }
        
        if (data) {
          config.data = data
          config.header = {
            'Content-Type': 'application/json'
          }
        }
        
        uni.request(config)
      })
    },
    
    // 添加测试结果
    addResult(title, message, details = '', success = true) {
      this.testResults.unshift({
        title,
        message,
        details,
        success,
        timestamp: Date.now()
      })
      
      // 限制结果数量
      if (this.testResults.length > 20) {
        this.testResults = this.testResults.slice(0, 20)
      }
    },
    
    // 清空测试结果
    clearResults() {
      this.testResults = []
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.test-subscription-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
}

.page-header {
  text-align: center;
  padding: 40rpx 0;
  
  .page-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 12rpx;
  }
  
  .page-subtitle {
    display: block;
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.info-card, .result-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .card-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .clear-btn {
      padding: 8rpx 16rpx;
      font-size: 24rpx;
      color: #666;
      background: #f5f5f5;
      border-radius: 8rpx;
      border: none;
      
      &::after {
        border: none;
      }
    }
  }
}

.status-indicator {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-match {
    background: rgba(67, 233, 123, 0.1);
    .status-text { color: #43e97b; }
  }
  
  &.status-mismatch {
    background: rgba(255, 71, 87, 0.1);
    .status-text { color: #ff4757; }
  }
  
  &.status-unknown {
    background: rgba(153, 153, 153, 0.1);
    .status-text { color: #999; }
  }
}

.config-info {
  .config-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .config-label {
      font-size: 28rpx;
      color: #666;
    }
    
    .config-value {
      font-size: 26rpx;
      color: #333;
      font-family: monospace;
      max-width: 400rpx;
      word-break: break-all;
    }
  }
}

.test-steps {
  .step-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    
    &.step-completed {
      border-left: 6rpx solid #43e97b;
    }
    
    &.step-disabled {
      opacity: 0.6;
      pointer-events: none;
    }
    
    .step-header {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      
      .step-number {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        font-size: 28rpx;
        font-weight: bold;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
      }
      
      .step-title {
        flex: 1;
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
      }
      
      .step-status {
        font-size: 32rpx;
      }
    }
    
    .step-content {
      padding-left: 80rpx;
      
      .step-desc {
        display: block;
        font-size: 26rpx;
        color: #666;
        margin-bottom: 20rpx;
        line-height: 1.5;
      }
      
      .step-btn {
        padding: 16rpx 32rpx;
        border-radius: 8rpx;
        font-size: 28rpx;
        border: none;
        
        &::after {
          border: none;
        }
        
        &.primary {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
        }
        
        &.success {
          background: linear-gradient(135deg, #43e97b 0%, #38d9a9 100%);
          color: #fff;
        }
        
        &.default {
          background: #f5f5f5;
          color: #666;
          margin-left: 20rpx;
        }
        
        &[disabled] {
          opacity: 0.5;
        }
      }
      
      .send-options {
        display: flex;
        flex-wrap: wrap;
        gap: 20rpx;
      }
    }
  }
}

.results-scroll {
  max-height: 600rpx;
  
  .result-item {
    padding: 20rpx;
    border-radius: 12rpx;
    margin-bottom: 16rpx;
    
    &.result-success {
      background: rgba(67, 233, 123, 0.1);
      border-left: 4rpx solid #43e97b;
    }
    
    &.result-error {
      background: rgba(255, 71, 87, 0.1);
      border-left: 4rpx solid #ff4757;
    }
    
    .result-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;
      
      .result-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
      
      .result-time {
        font-size: 22rpx;
        color: #999;
      }
    }
    
    .result-content {
      .result-text {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
      }
    }
    
    .result-details {
      margin-top: 12rpx;
      padding: 12rpx;
      background: rgba(0, 0, 0, 0.05);
      border-radius: 8rpx;
      
      .details-text {
        font-size: 22rpx;
        color: #999;
        font-family: monospace;
        word-break: break-all;
      }
    }
  }
}

.quick-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
  
  .action-btn {
    flex: 1;
    padding: 20rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    font-weight: bold;
    border: none;
    
    &::after {
      border: none;
    }
    
    &.diagnose {
      background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
      color: #fff;
    }
    
    &.flow {
      background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
      color: #333;
    }
  }
}
</style>
